package mysql

import (
	"sync"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

type config struct {
	Key             string        //for trace
	DSN             []string      //连库参数
	MaxOpen         int           //最大连接数
	MaxIdle         int           //最大空闲连接数
	ConnMaxLifetime time.Duration //连接超时
}

var (
	pools = sync.Map{}
)

func mysqlEngine(cfg *config) (*xorm.EngineGroup, error) {
	engine, ok := pools.Load(cfg.Key)
	if ok {
		return engine.(*xorm.EngineGroup), nil
	} else {
		engine, e := xorm.NewEngineGroup("mysql", cfg.DSN, xorm.RandomPolicy())
		if e != nil {
			return nil, e
		}
		engine.SetMaxOpenConns(cfg.MaxOpen)
		engine.SetMaxIdleConns(cfg.MaxIdle)
		engine.SetConnMaxLifetime(cfg.ConnMaxLifetime)

		// 时区
		timeLocation, _ := time.LoadLocation("Asia/Chongqing")
		engine.SetTZLocation(timeLocation)

		pools.Store(cfg.Key, engine)

		return engine, nil
	}
}
